package com.gexiaobao.pigeon.ui.fragment.mine.banking

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.App
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.OrderTypeListResponse
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentTranscationRecordBinding
import com.gexiaobao.pigeon.ui.adapter.BankCardListAdapter
import com.gexiaobao.pigeon.ui.fragment.mine.banking.activity.ActivityAccountOrderDetail
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 19:16
 * @Describe    : 交易记录
 */
class FragmentTransactionRecord : BaseFragment<MineBankingViewModel, FragmentTranscationRecordBinding>() {

    private var bigTypeList: ArrayList<String> = arrayListOf()
    private var bigTypeSelectPosition = 0
    private var orderTypeList: ArrayList<OrderTypeListResponse.ListBean> = arrayListOf()
    private var startTime = ""
    private var endTime = ""
    private var pageSize = 20
    private val mAdapter: BankCardListAdapter by lazy { BankCardListAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>

    var timeTypeList = arrayListOf(
        App.instance.applicationContext.getString(R.string.mine_account_transaction_activity_time_type_all),
        App.instance.applicationContext.getString(R.string.mine_account_transaction_activity_time_type_one_month),
        App.instance.applicationContext.getString(R.string.mine_account_transaction_activity_time_type_one_week)
    )

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("交易记录") {
            nav().navigateUp()
        }

        mDatabind.transactionBigType.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {}

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                try {
                    if (orderTypeList.isNotEmpty()) {
                        bigTypeSelectPosition = orderTypeList[position-1].value
                    }
                    loadsir.showLoading()
                    mViewModel.getOrderList(true, pageSize, bigTypeSelectPosition, startTime, endTime)
                } catch (e: Exception) {
                    LogUtils.debugInfo(getString(R.string.mine_account_transaction_activity_get_type_err))
                }
            }
        })

        mDatabind.transactionTimeType.attachDataSource(timeTypeList)
        mDatabind.transactionTimeType.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {}

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                try {
                    val timePosition = timeTypeList[position]
                    when (timePosition) {
                        resources.getString(R.string.mine_account_transaction_activity_time_type_all) -> {
                            startTime = ""
                            endTime = ""
                        }

                        resources.getString(R.string.mine_account_transaction_activity_time_type_one_month) -> {
                            startTime = DatetimeUtil.getOldDate(-30).toString()
                            endTime = DatetimeUtil.getTimeString()
                        }

                        resources.getString(R.string.mine_account_transaction_activity_time_type_one_week) -> {
                            startTime = DatetimeUtil.getOldDate(-7).toString()
                            endTime = DatetimeUtil.getTimeString()
                        }
                    }
                    loadsir.showLoading()
                    mViewModel.getOrderList(true, pageSize, bigTypeSelectPosition, startTime, endTime)
                    LogUtils.debugInfo("$startTime---->>:$timePosition----->>:$endTime")
                } catch (e: Exception) {
                    LogUtils.debugInfo(getString(R.string.mine_account_transaction_activity_select_time_err))
                }
            }
        })

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 5f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getOrderList(false, pageSize, bigTypeSelectPosition, startTime, endTime)
            }
        }

        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getOrderList(true, pageSize, bigTypeSelectPosition, startTime, endTime)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getOrderList(true, pageSize, bigTypeSelectPosition, startTime, endTime)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivityAccountOrderDetail>("orderId" to mAdapter.data[position].orderId)
//            nav().navigateAction(R.id.action_to_order_detail, Bundle().apply {
//                putInt("orderId", mAdapter.data[position].orderId)
//            })
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.getOrderTypeList()
        loadsir.showLoading()
        mViewModel.getOrderList(true, pageSize, bigTypeSelectPosition, startTime, endTime)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.orderListResult.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }

        /** 获取订单类型列表 */
        mViewModel.orderTypeResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                if (!it.isEmpty()) {
                    if (!it.isEmpty()) {
                        orderTypeList.clear()
                        orderTypeList.addAll(it.list)
                        bigTypeList.clear()
                        bigTypeList.add(0, "全部")
                        it.list.forEachIndexed { _, listBean ->
                            bigTypeList.add(listBean.label)
                        }
                        mDatabind.transactionBigType.attachDataSource(bigTypeList)
                    } else {
                        RxToast.showToast("未获取到相关数据")
                    }
                }
            }, {
                RxToast.showToast(it.msg)
            })
        }
    }
}